package com.jsgt.greekfire.common.websocket

import com.jsgt.greekfire.ENV_PRO
import com.jsgt.greekfire.ENV_TYPE
import com.jsgt.greekfire.WEB_SOCKET_URL
import com.jsgt.greekfire.WEB_SOCKET_URL_TEST
import com.jsgt.greekfire.common.websocket.MyWebSocketClient.OnSocketListener
import java.net.URI

class MyWebSocketClientManager private constructor() {

    fun createClient(symbol: String): MyWebSocketClient {
        return if (symbolTemp == symbol && client != null) {
            client as MyWebSocketClient
        }else {
            symbolTemp = symbol
            closeConnect()
            var url: String? = WEB_SOCKET_URL_TEST
            if (ENV_TYPE == ENV_PRO) {
                url = WEB_SOCKET_URL
            }
            client = MyWebSocketClient(URI.create(url + symbol))

            client as MyWebSocketClient
        }
    }

//    fun createClient(): MyWebSocketClient {
//        if (client == null) {
//            var url: String? = WEB_SOCKET_URL_TEST
//            if (ENV_TYPE == ENV_PRO) {
//                url = WEB_SOCKET_URL
//            }
//            client = MyWebSocketClient(URI.create(url))
//        }
//        return client as MyWebSocketClient
//    }

    /**
     * 移除一个监听，判断client是否还持有监听，没有则断开连接
     *
     * @param onSocketListener
     */
    fun destroyClient(onSocketListener: OnSocketListener?) {
        if (client == null) {
            return
        }
        client!!.removeOnSocketListener(onSocketListener)
        if (!client!!.hasListener()) {
            closeConnect()
        }
    }

    /**
     * 断开连接
     */
    private fun closeConnect() {
        try {
            if (null != client) {
                client!!.close()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            client = null
        }
    }

    companion object {
        private var symbolTemp:String ? = null
        private var client: MyWebSocketClient? = null

        val instance: MyWebSocketClientManager
            get() = MyWebSocketClientManager()
    }
}